package com.qianfeng.openapi.zuul.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qianfeng.openapi.zuul.exception.ExceptionDict;
import com.qianfeng.openapi.zuul.feign.CacheServiceClient;
import com.qianfeng.openapi.zuul.utils.SysConstant;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2021/1/4
 * @Time: 下午3:15
 */
@Component
public class LimitFilter extends ZuulFilter {

    @Resource
    private CacheServiceClient cacheServiceClient;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 3;
    }

    @Override
    public boolean shouldFilter() {
        return RequestContext.getCurrentContext().sendZuulResponse();
    }

    @Override
    public Object run() throws ZuulException {
        //1.得到总的访问限定数
        RequestContext context = RequestContext.getCurrentContext();
        String limit = context.get(SysConstant.LIMIT)+"";//
        int totalLimit = Integer.parseInt(limit);
        //2.当前该app 访问api的次数。
        // COUNT:561AC1A8676CFCB0CC61B041AE42ABB8
        String appKey = context.getRequest().getParameter(SysConstant.APPKEY);
        String key = SysConstant.CACHE_COUNT+appKey;
        String c =  cacheServiceClient.get(key);
        int currentCount = 0;
        if (StringUtils.isBlank(c)){
            //第一次访问
            currentCount=1;
            cacheServiceClient.set(key,currentCount+"");

            long  now = System.currentTimeMillis();

            Calendar calendar = new GregorianCalendar();
            calendar.set(Calendar.YEAR,calendar.get(Calendar.YEAR));
            calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH));
            calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH));
            calendar.set(Calendar.HOUR_OF_DAY,23);//24
            calendar.set(Calendar.MINUTE,59);
            calendar.set(Calendar.SECOND,59);

            Date date =  calendar.getTime();
            long end = date.getTime();

            long expire = (end-now)/1000;// 计算离当天最后一秒还有多少秒
            cacheServiceClient.expire(key,Integer.valueOf(expire+""));
        }else{
            currentCount= Integer.parseInt(c);
            if (currentCount>=totalLimit){
                context.getResponse().setContentType("application/json;charset=utf-8");//响应内容类型  防止乱码
                context.setSendZuulResponse(false);
                context.setResponseStatusCode(HttpStatus.BAD_REQUEST.value());
                Map<String,Object> map = new HashMap<>();
                map.put("code",ExceptionDict.LIMIT_ERROR);//错误码
                map.put("msg","您已经超过今天的限制次数了，请明天再调用");//错误信息

                String json = JSON.toJSONString(map);

                context.setResponseBody(json);

            }else{
               long t =  cacheServiceClient.getAutoIncreId(key);
                System.out.println("访问前："+currentCount+"访问后："+t+" 总的"+totalLimit);
            }
        }



        return null;
    }
}